package edu.java.ishop.web;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.WebApplicationContextUtils;

import edu.java.ishop.model.Product;
import edu.java.ishop.model.ProductCategory;
import edu.java.ishop.services.ProductService;

public class MainServlet extends HttpServlet {

	private ProductService productService = null;

	@Override
	public void init() throws ServletException {
		//for IOC container,chtobu he uchitival
		productService = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext()).getBean(
						ProductService.class);
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		final List<Product> all = productService.getAll();
		req.setAttribute("products", all);
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher("/products.jsp");
		dispatcher.forward(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Product product = new Product();
		ProductCategory prCategory = new ProductCategory();
		product.setId(Long.parseLong(req.getParameter("id")));
		product.setName(req.getParameter("name"));
		product.setPrice(BigDecimal.valueOf(Double.parseDouble(req
				.getParameter("price"))));
		product.setDescription(req.getParameter("description"));
		prCategory.setId(Long.parseLong(req.getParameter("id")));
		prCategory.setName(req.getParameter("category"));
		product.setCategory(prCategory);

		productService.save(product);
		doGet(req, resp);
	}
}
